package ch.comtools.ssh.datatype;

import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;

/**
 * Name List (as specified in RFC4251#Section-5)
 * <p>
 * A string containing a comma-separated list of names.  A name-list
 * is represented as a uint32 containing its length (number of bytes
 * that follow) followed by a comma-separated list of zero or more
 * names.  A name MUST have a non-zero length, and it MUST NOT
 * contain a comma (",").  As this is a list of names, all of the
 * elements contained are names and MUST be in US-ASCII.  Context may
 * impose additional restrictions on the names.  For example, the
 * names in a name-list may have to be a list of valid algorithm
 * identifiers (see Section 6 below), or a list of [RFC3066] language
 * tags.  The order of the names in a name-list may or may not be
 * significant.  Again, this depends on the context in which the list
 * is used.  Terminating null characters MUST NOT be used, neither
 * for the individual names, nor for the list as a whole.
 * </p>
 * @author Roger Dudler <roger.dudler@gmail.com>
 * @since 1.0
 * @version $Id$
 */
public class NameList {

	private List<String> entries = new ArrayList<String>();
	private int length;
	private String encoding = "US-ASCII";
	
	public NameList() {
		// TODO Auto-generated constructor stub
	}
	
	/**
	 * @param entry
	 */
	public NameList(String entry) {
		this.add(entry);
	}
	
	/**
	 * @param length
	 */
	public NameList(int length) {
		this.length = length;
	}
	
	/**
	 * @param entry
	 */
	public void add(String entry) {
		// TODO check string
		try {
			byte[] bytes = entry.getBytes(this.encoding);
			if (this.getEntries().size() > 0) {
				this.length += bytes.length + 1;
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		this.entries.add(entry);
	}
	
	/**
	 * Get bytes for use in a packet.
	 */
	public ByteBuffer getBytes() {
		int i = 0;
		ByteBuffer data = ByteBuffer.allocateDirect(this.length + 4);
		data.putInt(this.length);
		for (String entry : this.getEntries()) {
			try {
				if (this.getEntries().size() > 0 && i > 0) {
					entry = entry + ",";
					data.put(entry.getBytes(this.encoding));
				}
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			i++;
		}
		return data;
	}
	
	/**
	 * @return
	 */
	public List<String> getEntries() {
		return this.entries;
	}
	
	/**
	 * Get bytes of strings.
	 * @return
	 */
	public int getLength() {
		return this.length;
	}
	
	/**
	 * @see java.lang.Object#toString()
	 */
	@Override
	public String toString() {
		int i = 0;
		String string = "NameList {";
		for (String entry : this.getEntries()) {
			string += entry;
			if (i > 0) {
				string += ",";
			}
			i++;
		}
		string += "}";
		return string;
	}

}
